package com.xinyue.game.utils.encrypt;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @Author 王广帅
 * @Date 2021/4/11 13:38
 */
public class GzipUtil {

    /**
     * 压缩数据
     *
     * @param data
     * @return
     */
    public static byte[] compress(byte[] data) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream(data.length);
        GZIPOutputStream gzip = new GZIPOutputStream(out, data.length);
        gzip.write(data);
        gzip.close();//必须先关闭它
        return out.toByteArray();

    }

    /**
     * 解压数据
     *
     * @param data
     * @return
     */
    public static byte[] uncompress(byte[] data) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(data);
        GZIPInputStream gin = new GZIPInputStream(in, data.length);
        byte[] buffer = new byte[1024];
        int n;
        while ((n = gin.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();

    }
}
